package com.example.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;

public class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

    // 在bean被实例化之前，ioc容器会调用该方法
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        System.out.println("MyInstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()方法被调用, beanClass:" + beanClass + ", beanName:" + beanName);
        return null;
    }

    // 在bean被实例化之后且在给bean注入属性之前, ioc会调用该方法
    // 正常的话应该返回true，如果返回false，那么这个bean的后续的属性填充和属性依赖注入【populateBean】将不会执行，
    // 同时后续的postProcessProperties()将不会执行,但是BeanPostProcessor的两个方法仍然会执行。
    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        System.out.println(String.format("MyInstantiationAwareBeanPostProcessor.postProcessAfterInstantiation()被调用，bean:%s, beanName:%s", bean.toString(), beanName));
        return true;
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        System.out.println(String.format("MyInstantiationAwareBeanPostProcessor.postProcessProperties()方法被调用pvs:%s, bean:%s, beanName:%s", pvs.toString(), bean.toString(), beanName));
        return null;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println(String.format("MyInstantiationAwareBeanPostProcessor.postProcessBeforeInitialization()被调用，bean:%s, beanName:%s", bean.toString(), beanName));
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println(String.format("MyInstantiationAwareBeanPostProcessor.postProcessAfterInitialization()被调用，bean:%s, beanName:%s", bean.toString(), beanName));
        return bean;
    }
}
